<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="form" :model="search" :inline="true">
        <el-form-item label="商品类型搜索：">
          <el-input
            v-model="search.className"
            clearable
            placeholder="请输入"
            size="medium"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="medium"
            class="my-primary1"
            icon="el-icon-search"
            @click="query"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-row type="flex" class="operation">
        <el-button
          type="primary"
          class="my-primary2"
          icon="el-icon-circle-plus-outline"
          @click="showAdd('add')"
        >新建</el-button>
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
      >
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80px"
        />
        <el-table-column prop="className" label="商品类型名称" />
        <el-table-column label="操作" width="150">
          <template v-slot="{ row }">
            <el-button
              type="text"
              class="el-button--primary-text"
              @click.native="recreate(row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              class="el-button--danger-text"
              @click.native="delGoodType(row.classId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          :total="totalCount"
          :page-size="search.pageSize"
          prev-text="上一页"
          next-text="下一页"
          hide-on-single-page
          @current-change="vmTypeSearch"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增商品类型"
      :visible.sync="addDialog"
      width="630px"
      top="15vh"
      @close="addClose"
    >
      <el-form
        ref="add"
        :model="addForm"
        :rules="addRules"
        label-width="140px"
        size="medium"
      >
        <el-form-item label="商品类型名称：" prop="className">
          <el-input
            v-model="addForm.className"
            autocomplete="off"
            placeholder="请输入"
            style="width: 396px"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="16">
              <el-button class="my-secondary" @click="addClose">取消</el-button>
              <el-button
                type="primary"
                class="my-primary2"
                @click="addSubmit"
              >确认</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchRegionList, getVmTypeList, addGoodType, updateGoodType, delGoodType
} from '@/api/vm'
import { getRoleList } from '@/api/user'
export default {
  data() {
    return {
      search: {
        className: '',
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      totalCount: 0,
      totalPage: 0,
      addDialog: false,
      addForm: {
        className: ''
      },
      addRules: {
        className: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      type: '',
      roles: [],
      regions: [],
      currentId: null
    }
  },
  async created() {
    await this.vmTypeSearch()
  },
  methods: {
    query() {
      this.search.pageIndex = 1
      this.vmTypeSearch()
    },
    async vmTypeSearch() {
      const { currentPageRecords, totalCount, totalPage } = await getVmTypeList({
        ...this.search
      })
      this.totalCount = parseInt(totalCount)
      this.totalPage = totalPage
      this.tableData = currentPageRecords
    },
    formattedDate(date) {
      const currentDate = new Date(date)
      const year = currentDate.getFullYear()
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
      const day = ('0' + currentDate.getDate()).slice(-2)
      const hours = ('0' + currentDate.getHours()).slice(-2)
      const minutes = ('0' + currentDate.getMinutes()).slice(-2)
      const seconds = ('0' + currentDate.getSeconds()).slice(-2)
      return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
    },
    async showAdd(type) {
      this.addDialog = true
      this.type = type
      this.roles = await getRoleList()
      const { currentPageRecords } = await searchRegionList({ pageIndex: 1, pageSize: 100000 })
      this.regions = currentPageRecords
    },
    addClose() {
      this.addDialog = false
      this.$refs.add.resetFields()
      this.addForm = {
        className: ''
      }
    },
    async addSubmit() {
      this.$refs.add.validate(async(isOK) => {
        if (isOK) {
          if (this.type === 'add') {
            await addGoodType({ ...this.addForm })
          } else {
            await updateGoodType({ ...this.addForm }, this.currentId)
          }
          this.addClose()
          this.vmTypeSearch()
        }
      })
    },
    async recreate(row) {
      this.addForm = { ...row }
      this.currentId = row.id
      this.showAdd('edit')
    },
    async delGoodType(id) {
      this.$confirm('您确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delGoodType(id)
        if (this.tableData.length === 1) this.search.pageIndex--
        this.vmTypeSearch()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/common.scss";
</style>
